using CoreManager.Models.DTOs;
using CoreManager.Services.Users;
using Microsoft.AspNetCore.Mvc;
using CoreManager.API.Common;

namespace CoreManager.API.Controllers
{
    /// <summary>
    /// 用户管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class UsersController : BaseController
    {
        private readonly IUserService _userService;
        private readonly ILogger<UsersController> _logger;

        public UsersController(
            IUserService userService,
            ILogger<UsersController> logger) : base(logger)
        {
            _userService = userService;
            _logger = logger;
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="userName">用户名</param>
        /// <param name="realName">真实姓名</param>
        /// <param name="email">邮箱</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetUsers(
            int pageIndex = 1, 
            int pageSize = 20,
            string? userName = null,
            string? realName = null,
            string? email = null,
            int? status = null)
        {
            var result = await _userService.GetUsersAsync(pageIndex, pageSize, userName, realName, email, status);
            
            if (result.Code == 200)
            {
                return Success(result.Data, result.Message);
            }
            
            return Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 根据ID获取用户
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetUser(int id)
        {
            var result = await _userService.GetUserByIdAsync(id);
            
            if (result.Code == 200)
            {
                return Success(result.Data, result.Message);
            }
            
            return Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="createDto">用户信息</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreateUser([FromBody] CreateUserDto createDto)
        {
            try
            {
                var currentUserId = GetCurrentUserId();
                var result = await _userService.CreateUserAsync(createDto, currentUserId);
                
                if (result.Code == 200)
                {
                    return Success(result.Data, result.Message);
                }
                
                return Fail(result.Message, result.Code);
            }
            catch (Exception ex)
            {
                return HandleException(ex, "创建用户");
            }
        }

        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <param name="updateDto">用户信息</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateUser(int id, [FromBody] UpdateUserDto updateDto)
        {
            try
            {
                var currentUserId = GetCurrentUserId();
                var result = await _userService.UpdateUserAsync(id, updateDto, currentUserId);
                
                if (result.Code == 200)
                {
                    return Success(result.Data, result.Message);
                }
                
                return Fail(result.Message, result.Code);
            }
            catch (Exception ex)
            {
                return HandleException(ex, $"更新用户失败，ID: {id}");
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteUser(int id)
        {
            try
            {
                var currentUserId = GetCurrentUserId();
                var result = await _userService.DeleteUserAsync(id, currentUserId);
                
                if (result.Code == 200)
                {
                    return Success(result.Message);
                }
                
                return Fail(result.Message, result.Code);
            }
            catch (Exception ex)
            {
                return HandleException(ex, $"删除用户失败，ID: {id}");
            }
        }

        /// <summary>
        /// 批量删除用户
        /// </summary>
        /// <param name="request">批量删除请求</param>
        /// <returns></returns>
        [HttpDelete("batch")]
        public async Task<IActionResult> BatchDeleteUsers([FromBody] BatchDeleteRequest request)
        {
            try
            {
                var currentUserId = GetCurrentUserId();
                var result = await _userService.BatchDeleteUsersAsync(request.Ids, currentUserId);
                
                if (result.Code == 200)
                {
                    return Success(result.Message);
                }
                
                return Fail(result.Message, result.Code);
            }
            catch (Exception ex)
            {
                return HandleException(ex, "批量删除用户");
            }
        }

        /// <summary>
        /// 重置用户密码
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <param name="request">重置密码请求</param>
        /// <returns></returns>
        [HttpPost("{id}/reset-password")]
        public async Task<IActionResult> ResetPassword(int id, [FromBody] ResetPasswordRequest request)
        {
            try
            {
                var currentUserId = GetCurrentUserId();
                var result = await _userService.ResetPasswordAsync(id, request.NewPassword, currentUserId);
                
                if (result.Code == 200)
                {
                    return Success(result.Message);
                }
                
                return Fail(result.Message, result.Code);
            }
            catch (Exception ex)
            {
                return HandleException(ex, $"重置用户密码失败，用户ID: {id}");
            }
        }

        /// <summary>
        /// 切换用户状态
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <param name="request">状态切换请求</param>
        /// <returns></returns>
        [HttpPost("{id}/toggle-status")]
        public async Task<IActionResult> ToggleUserStatus(int id, [FromBody] ToggleStatusRequest request)
        {
            try
            {
                var currentUserId = GetCurrentUserId();
                var result = await _userService.ToggleUserStatusAsync(id, request.Status, currentUserId);
                
                if (result.Code == 200)
                {
                    return Success(result.Message);
                }
                
                return Fail(result.Message, result.Code);
            }
            catch (Exception ex)
            {
                return HandleException(ex, $"切换用户状态失败，用户ID: {id}");
            }
        }

        /// <summary>
        /// 分配用户角色
        /// </summary>
        /// <param name="assignDto">用户角色分配DTO</param>
        /// <returns></returns>
        [HttpPost("assign-roles")]
        public async Task<IActionResult> AssignUserRoles([FromBody] AssignUserRolesDto assignDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest("请求参数无效");
                }

                var currentUserId = GetCurrentUserId();
                var result = await _userService.AssignUserRolesAsync(assignDto, currentUserId);
                
                if (result.Code == 200)
                {
                    return Success(result.Message);
                }
                
                return Fail(result.Message, result.Code);
            }
            catch (Exception ex)
            {
                return HandleException(ex, $"分配用户角色失败，用户ID: {assignDto.UserId}");
            }
        }

        /// <summary>
        /// 获取用户的角色列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        [HttpGet("{userId}/roles")]
        public async Task<IActionResult> GetUserRoles(int userId)
        {
            try
            {
                var result = await _userService.GetUserRolesAsync(userId);
                
                if (result.Code == 200)
                {
                    return Success(result.Data);
                }
                
                return Fail(result.Message, result.Code);
            }
            catch (Exception ex)
            {
                return HandleException(ex, $"获取用户角色失败，用户ID: {userId}");
            }
        }
    }
}
